package org.example.leetCode;

import java.util.Optional;

/**
 * @author Administrator
 */
public class MyAtoi {

    public static void main(String[] args) {
        String s = "42";
        int i = myAtoi(s);
        System.out.println(i);

    }

    public static int myAtoi(String s) {
        if (s.length() == 0||s==" "){
            return 0;
        }
            s = s.trim();
        int index = 0;
        int res = 0;
        int sign = 1;
        char[] chars = s.toCharArray();
        int length = chars.length;
        if (chars[index] == '-' || chars[index] == '+') {
            sign = chars[index] == '-' ? -1 : 1;
            index++;
        }
        for (; index < length; index++) {
            if ((s.charAt(index) - '0') >= 0 && (s.charAt(index) - '0') <= 9) {
                int temp = res * 10 + (s.charAt(index) - '0');
                if (temp - (s.charAt(index) - '0') / 10 < res) {
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                res = temp;
            } else {
                return res * sign;
            }
        }
        return res * sign;
    }
}
